<template>
  <!-- :style="{'overflow':show?'hidden':'auto'}" -->
  <div class="con_page" :style="{ overflow: show ? 'hidden' : 'auto' }">
    <user-card></user-card>
    <div class="info_box">
      <div class="info_box_title">预约医院</div>
      <div class="content">中国医科大学附属口腔医院({{info.hospitalName}})</div>
    </div>
    <div class="xian"></div>
    <div class="info_box">
      <div class="info_box_title">预约科室</div>
      <div class="content">{{ info.deptName }}</div>
    </div>
    <div class="xian"></div>
    <div class="info_box">
      <div class="info_box_title">预约医生</div>
      <div class="content">{{ info.doctorName }}</div>
    </div>
    <div class="xian"></div>
    <div class="info_box">
      <div class="info_box_title">就诊时间</div>
      <div class="content">
        {{ info.regDate }}
        {{ info.sctime }}
      </div>
    </div>
    <div class="gap"></div>
    <!--    <div class="info_box">-->
    <!--      <div class="info_box_title">挂号费</div>-->
    <!--      <div class="content">￥{{ info.regFee }}</div>-->
    <!--    </div>-->
    <div class="xian"></div>
    <div class="info_box">
      <div class="info_box_title">挂号费</div>
      <div class="content">￥{{ info.treatFee / 100 }}</div>
    </div>
    <div class="xian"></div>
    <div class="info_box">
      <div class="info_box_title">支付金额</div>
      <div class="content">
        <span style="color: red">￥{{ info.regFee | sum(info.treatFee) }}</span>
      </div>
    </div>
    <div class="explain_box">
      说明：<br/>
      1. 预约成功后，请在就诊当日提前到达相应预约科室<span style="color: #ff0000;">扫码签到</span>并候诊，未按预约时间就诊者可能造成延后诊治或改日诊治，改日诊治需重新预约挂号。<br>
      2. 如需取消预约，可于就诊日前1天的23:00前在系统内取消预约，费用将退回您所使用的支付账号内，就诊当日不可退号<br>
      3. <span style="color: #ff0000;">三甲医院医疗资源宝贵，预约号源如未提前取消，诊查费不予退还。请在挂号前务必确认好挂号科室和医生。</span><br>
      4. 我院实行<span style="color: #ff0000;">实名制就诊</span>，挂号信息必须和患者本人信息<span style="color: #ff0000;">保持一致</span>，否则不予接诊。<br>
      5. 医保提示：智慧医院线上预约挂号<span style="color: #ff0000;">不支持医保</span>挂号。如需使用医保卡支付后续治疗费用，可携带医保卡在医院收款窗口或自助机办理变更（挂号费仍为<span style="color: #ff0000;">自费不退</span>）<br>
    </div>
    <div class="agree_box">
      <img src="@/assets/img/xuanzhong@2x.png" alt="" v-if="agreeOK != false" @click="agreeFun"/>
      <img src="@/assets/img/weixuanzhong@2x.png" alt="" v-else @click="agreeFun"/>
      我已阅读并同意<span style="color: #4690ff" @click="goAgreement">《挂号协议》</span>
    </div>
    <div style="height: 55px"></div>
    <div class="btn_box">
      <div class="btn_box_1">
        合计：<span> ￥{{ info.regFee | sum(info.treatFee) }} </span>
      </div>
      <div class="btn_box_2" @click="orderReg">确认预约</div>
    </div>
    <popup v-model="show" height="100vh" :hide-on-blur="false" is-transparent>
      <div class="mask_confirm" style="">
        <div class="tit">温馨提示</div>
        <div class="content" v-html="onlineRegRemind" v-if="info.isOnline=='1'"></div>
        <div class="content" v-html="regRemind" v-else></div>
        <div class="btn" @click="show = !show">我已阅读并同意</div>
      </div>
    </popup>
  </div>
</template>
<script>
import userCard from "@/components/userCard.vue";
import {orderReg, payCreate, hospitalConfig, queryOrderStatus} from "@/api/api";
import {removeToken, getWxUserinfoCookies, removeWxUserinfoCookies} from "@/api/auth";
import {Popup} from "vux";
import Vue from "vue";

export default {
  components: {
    userCard,
    Popup,
  },
  data() {
    return {
      isPayClick: false,
      count: 0,
      info: {},
      userInfo: {},
      show: true,
      regRemind: "",
      onlineRegRemind: "",
      agreeOK: false,
    };
  },
  created() {
    console.log(this.$route.query);
    this.info = this.$route.query;
    if (window.localStorage.getItem("userInfo")) {
      this.userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
    } else {
      this.userInfo = JSON.parse(
        window.localStorage.getItem("defaultUserInfo")
      );
    }
    this.hospitalConfig();
  },
  methods: {
    orderReg() {

      const that = this;
      if (this.agreeOK == false) {
        // 请详细阅读并勾选挂号协议，即可预约挂号
        this.$vux.toast.text("请详细阅读并勾选挂号协议，即可预约挂号");
        return;
      }
      if (this.isPayClick) {
        console.log("请勿重复支付!")
        return;
      }
      this.isPayClick = true;
      setTimeout(function () {
        this.isPayClick = false;
      }, 2000);
      this.$vux.loading.show({text: '请求支付信息...'});
      if (this.info.deptName == "儿童口腔科") {
        if (that.getAge(that.userInfo.birthday) > 14) {
          this.$vux.loading.hide()
          that.$vux.confirm.show({
            // 组件除show外的属性
            content: "您的年龄,不适合挂儿科科室",
            confirmText: "我已阅读并同意",
            showCancelButton: false,
            onConfirm() {
            },
          });
          return;
        }
      } else if (this.info.deptName == "牙体牙髓病科"
        // || this.info.deptName == "牙周病科"
      ) {
        if (that.getAge(that.userInfo.birthday) < 15) {
          this.$vux.loading.hide()
          that.$vux.confirm.show({
            // 组件除show外的属性
            content: "14周岁以下建议前往儿童口腔科或口腔预防科就诊",
            confirmText: "我已阅读并同意",
            showCancelButton: false,
            onConfirm() {
            },
          });
          return;
        }
      }
      var data = {
        deptId: that.info.deptId,
        doctorId: that.info.doctorId,
        regDate: that.info.regDate,
        timeFlag: that.info.timeFlag,
        hospPatientId: that.userInfo.hospPatientId,
        regId: that.info.regId,
        regFee: that.info.regFee,
        treatFee: that.info.treatFee,
        roomName: that.info.roomName,
        isOnline: that.info.isOnline
      };

      orderReg(data).then((res) => {
        if (res.code == 200) {
          // alert("预挂号成功");
          // 获取微信支付配置
          // that.$router.push({
          //   path: "/registration_record_unpaid",
          //   query: {
          //     orderId: res.data.hospOrderId,
          //   },
          // });
          that.payCreate(res.data.hospOrderId);
        } else if (res.code == 1355) {
          this.$vux.toast.text(res.message);
          // that.$router.replace({
          //   name: "registration_record",
          // });
        }
      });
    },
    goLogin() {
      try {
        console.log("清理localStorage");
        localStorage.clear();
      } catch (err) {
        console.log("清理localStorage失败:" + err);
      }
      try {
        console.log("清理token");
        removeToken();
        removeWxUserinfoCookies();
      } catch (err) {
        alert(err)
        console.log(err);
      }
      try {
        console.log("清理openId");
        window.localStorage.removeItem("openId");
      } catch (err) {
        alert(err)
        console.log(err);
      }
      this.$router.push({path: "/"});
    },
    getLocalOpenId() {
      try {
        var user = JSON.parse(getWxUserinfoCookies());
        if (user && user.openid.trim().length > 0) {
          return user.openid;
        } else {
          console.log("getWxUserinfoCookies 未获取到微信openid");
        }
      } catch (err) {
        console.log(err)
        var openId = window.localStorage.getItem("openId");
        return openId;
      }
    },
    payCreate(hospOrderId) {
      var openId = this.getLocalOpenId();
      const that = this;
      payCreate({
        orderType: "1",
        orderId: hospOrderId,
        openId: openId,
      }).then((res) => {
        this.isPayClick = false;
        if (res.code == 200) {
          // 调起微信支付
          that.wxPay(res.data, hospOrderId);
        } else {
          alert(res.message);
          if (res.code == 1355) {
            that.$router.replace({
              name: "registration_record",
            });
          }
        }
      });
    },
    // 发起微信支付
    wxPay(data, hospOrderId) {
      this.$vux.loading.hide();
      const that = this;
      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign, //微信签名
        },
        function (response) {
          //TODO 应该再进行一次查单验证来保证支付成功
          if (response.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回get_brand_wcpay_request:ok，但并不保证它绝对可靠。
            that.$vux.loading.show()
            that.queryOrderStatusFun(hospOrderId)

          } else {
            alert("支付失败");
            that.$router.push({
              name: "registration_record",
            });
          }
        }
      );
    },
    queryOrderStatusFun(orderId) {
      queryOrderStatus({
        orderId, //订单号
        "orderType": "1" //1:挂号 2:缴费
      }).then(res => {
        this.count++
        // 轮询6次
        if (this.count < 6) {
          if (res.code == 200) {
            this.$vux.loading.hide()
            alert("挂号成功")
            this.$router.push({
              path: "/registration_record_appo",
              query: {
                orderId,
                pactname: "智慧医院"
              },
            });
            return
          } else if (res.code == 400) {
            if (res.message == 'NOTIFY_HIS_ERROR') {
              alert("通知his失败");
              this.$vux.loading.hide()
              this.count = 0
              return
            } else {
              setTimeout(() => {
                this.queryOrderStatusFun(orderId)
              }, 2000)
            }

          }
        } else {
          alert("通知his失败");
          this.$vux.loading.hide()
          this.count = 0
          return
        }

      })
    },
    agreeFun() {
      this.agreeOK = !this.agreeOK;
    },
    goAgreement() {
      this.$router.push({
        path: "/registration_agreement",
      });
    },
    hospitalConfig() {
      hospitalConfig().then((res) => {
        if (res.code == 200) {
          this.regRemind = res.data.regRemind;
          this.onlineRegRemind = res.data.onlineRegRemind;
        }
      });
    },
    getAge(strBirthday) {
      var returnAge;

      var strBirthdayArr = strBirthday.split("-");

      var birthYear = strBirthdayArr[0];

      var birthMonth = strBirthdayArr[1];

      var birthDay = strBirthdayArr[2];

      var d = new Date();

      var nowYear = d.getFullYear();

      var nowMonth = d.getMonth() + 1;

      var nowDay = d.getDate();

      if (nowYear == birthYear) {
        returnAge = 0; //同年 则为0岁
      } else {
        var ageDiff = nowYear - birthYear; //年之差

        if (ageDiff > 0) {
          if (nowMonth == birthMonth) {
            var dayDiff = nowDay - birthDay; //日之差

            if (dayDiff < 0) {
              returnAge = ageDiff - 1;
            } else {
              returnAge = ageDiff;
            }
          } else {
            var monthDiff = nowMonth - birthMonth; //月之差

            if (monthDiff < 0) {
              returnAge = ageDiff - 1;
            } else {
              returnAge = ageDiff;
            }
          }
        } else {
          returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
        }
      }

      return returnAge; //返回周岁年龄
    },
  },
  filters: {
    sum(regFee, treatFee) {
      var totalFee = (parseInt(regFee) + parseInt(treatFee)) / 100;
      return totalFee;
    },
    timeTo(timeFlag) {
      var str = ""
      switch (timeFlag) {
        case 1:
          str = "08:00-11:30"
          break;
        case 2:
          str = "13:00-16:30"
          break;
        case 11:
          str = "08:00-9:00"

          break;
        case 12:
          str = "09:00-10:00"
          break;
        case 13:
          str = "10:00-11:00"
          break;
        case 21:
          str = "13:00-14:00"
          break;
        case 22:
          str = "14:00-15:00"
          break;
        case 23:
          str = "15:00-16:00"
          break;

        default:
          break;
      }
      return str
    },
  },
};
</script>
<style scoped>
.con_page {
  height: 100vh;
}

.con_page .info_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: calc(100% - 32px);
  padding: 15px 16px;
}

.con_page .info_box .info_box_title {
  color: #a4adbe;
}

.xian {
  margin: 0 16px;
  width: calc(100% - 32px);

  height: 1px;
  background: #e7ecf5;
}

.gap {
  width: 100%;
  height: 12px;
  background: #f4f8fc;
}

.explain_box {
  padding: 16px;
  background-color: #f4f8fc;
  color: #8a93a7;
  font-size: 14px;
  /* min-height: 300px; */
  line-height: 24px;
}

.agree_box {
  display: flex;
  align-items: center;
  width: calc(100% - 2rem);
  padding: 0rem 1rem 2rem 1rem;
  background-color: #f4f8fc;
  font-size: 0.9375rem;
}

.agree_box img {
  width: 1.125rem;
  height: 1.125rem;
  margin-right: 0.75rem;
}

.btn_box {
  height: 55px;
  width: 100%;
  background-color: #fff;
  display: flex;
  position: fixed;
  bottom: 0;
}

.btn_box .btn_box_1 {
  width: calc(100% - 140px);
  height: 100%;
  font-size: 16px;
  line-height: 55px;
  text-indent: 1rem;
}

.btn_box .btn_box_1 span {
  font-size: 18px;
  color: red;
}

.btn_box .btn_box_2 {
  width: 140px;
  height: 100%;
  line-height: 55px;
  font-size: 18px;
  background: linear-gradient(90deg, #448eff 0%, #66a3ff 100%);
  color: #fff;
  text-align: center;
  font-weight: bold;
}

.mask_confirm {
  width: 90%;
  background-color: #fff;
  height: 70%;
  margin: 0 auto;
  border-radius: 5px;
  position: fixed;
  left: 5%;
  top: 10%;
  /* position: relative; */
}

.mask_confirm .tit {
  height: 45px;
  line-height: 45px;
  text-align: center;
  border-bottom: 1px solid #e7ecf5;
  font-size: 18px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #448eff;
}

.mask_confirm .content {
  padding: 0px 16px;
  margin: 20px 0;
  height: 66%;
  overflow-y: auto;
  line-height: 1.5rem;
}

.mask_confirm .btn {
  position: absolute;
  bottom: 15px;
  left: calc((100% - 162px) / 2);
  width: 162px;
  height: 44px;
  text-align: center;
  line-height: 44px;
  background: linear-gradient(90deg, #448eff 0%, #66a3ff 100%);
  border-radius: 3px;
  font-size: 18px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #ffffff;
}
</style>
<style>
.mask_confirm p {
  margin-block-start: 0em !important;
  margin-block-end: 0em !important;
  word-wrap: break-word;
}
</style>
